/**
 * 主入口
 * 以Cycle.run() 开始执行
 * 以history作为路由
 */

import xs from 'xstream';
import { setup, run } from '@cycle/run';
import { restartable, rerunner } from 'cycle-restart';
import { makeDOMDriver } from '@cycle/dom';
import { makeHTTPDriver } from '@cycle/http';
import { timeDriver } from '@cycle/time';
import isolate from '@cycle/isolate';
import storageDriver from '@cycle/storage';
import { captureClicks, makeHistoryDriver } from '@cycle/history';
import onionify from 'cycle-onionify';
import storageify from 'cycle-storageify';


import { Component, Sources, RootSinks } from './page/types';
// import { App } from './page/App';
import App from './page/App';

// 引入css
// require('todomvc-common/base.css');
// require('todomvc-app-css/index.css');

/**
 * main 函数
 * onionify: cycle的状态管理
 */
const main : Component = onionify(storageify(App, {key: 'todomvc-cycle'}));

/**
 * driver
 * 类似服务
 */
let drivers : any, driverFn : any;
/// #if PRODUCTION
drivers = {
    DOM: makeDOMDriver('#app'),
    HTTP: makeHTTPDriver(),
    Time: timeDriver,
    history: captureClicks(makeHistoryDriver()),
    storage: storageDriver
};
/// #else
driverFn = () => ({
    DOM: restartable(makeDOMDriver('#app'), { pauseSinksWhileReplaying: false }),
    HTTP: restartable(makeHTTPDriver()),
    Time: timeDriver,
    history: captureClicks(makeHistoryDriver()),
    storage: storageDriver
});
/// #endif
export const driverNames : string[] = Object.keys(drivers || driverFn());

/// #if PRODUCTION
run(main as any, drivers);
/// #else
const rerun = rerunner(setup, driverFn, isolate);
rerun(main as any);

if (module.hot) {
    module.hot.accept('./page/App', () => {
        const newApp = require('./page/App').App;

        rerun(onionify(storageify(App, {key: 'todomvc-cycle'})));
    });
}
/// #endif
